package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strings"
	"time"
	"weiboxs.com/new_h_glasses/utils"
)

type Retails struct {
	Id             int64
	DepartmentId   int64
	Archives       *Archives  `orm:"rel(fk);null;on_delete(set_null)"`
	Optometry      *Optometry `orm:"rel(fk);null;on_delete(set_null)"`
	ManualNumber   string
	BusinessName   string
	TotalMoney     float64 //总金额
	ChangesMoney   float64 //优惠金额
	SumPayable     float64 //应付金额
	AlreadyMoney   float64 //已付金额
	IsPayment      int     //支付状态1未付2待取货3部分退货4已退货5已完成
	AlipayMoney    float64 //支付宝
	WechatMoney    float64 //微信支付
	CardMoney      float64 //刷卡支付
	CashMoney      float64 //现金
	PickUpType     int     //取镜方式1现场取镜2邮递取镜3指定日期取镜
	HopePickUpTime int64   //取镜时间
	AddressName    string  //邮递地址
	PostCompany    string  //快递公司
	PostNumber     string  //快递单号
	PostMoney      float64 //快递金额
	PostPaytype    int     //快递类型1到付2寄付
	PostUser       string  //收件人姓名
	PostMobile     string  //收件人手机
	Remarks        string
	CreatedAt      int64
	UpdatedAt      int64
	CreatedBy      string
	UpdatedBy      string
	RetailsData    []*RetailsData `orm:"reverse(many);null"`
}

type RetailsQueryParam struct {
	BaseQueryParam
	ManualNumber   string `json:"manual_number"` //单号
	ArchivesName   string                        //客户名
	ArchivesMobile string                        //客户手机
	StartDate      string                        //开始日期
	EndDate        string                        //结束日期
	PickUpType     string `json:"pick_up_type"`  //取镜方式
	OptId          int64                         //验光
	ArcId          int64                         //档案
	IsPayment      string                        //支付状态
	CreatedBy      string                        //操作人
	Depid          int64
	Business       string //营业员
}

func (a *Retails) TableName() string {
	return RetailsTableName()
}

func RetailsTableName() string {
	return TableName("sa_retails")
}

//查询列表数据
func RetailsList(params *RetailsQueryParam) []*Retails {

	query := orm.NewOrm().QueryTable(RetailsTableName()).RelatedSel("Archives")
	data := make([]*Retails, 0)

	if params.ArcId > 0 {
		query = query.Filter("archives_id", params.ArcId)
	}
	if len(params.IsPayment) > 0 { //已支付
		sp := strings.Split(params.IsPayment, ",")
		query = query.Filter("IsPayment__in", sp)
	}

	if len(params.ArchivesName) > 0 {
		query = query.Filter("Archives__Realname", params.ArchivesName)
	}
	if len(params.ArchivesMobile) > 0 {
		query = query.Filter("Archives__Mobile", params.ArchivesMobile)
	}
	if len(params.Business) > 0 {
		query = query.Filter("business_name", params.Business)
	}

	if len(params.StartDate) > 0 {
		query = query.Filter("created_at__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		query = query.Filter("created_at__lte", utils.GetDateParse(params.EndDate)+86400)
	}

	if len(params.CreatedBy) > 0 {
		query = query.Filter("CreatedBy", params.CreatedBy)
	}

	if len(params.PickUpType) > 0 {
		query = query.Filter("pick_up_type", params.PickUpType)
	}
	if len(params.ManualNumber) > 0 {
		query = query.Filter("manual_number", params.ManualNumber)
	}

	query = query.Filter("department_id", params.Depid)

	query.OrderBy("-id").All(&data)

	return data
}

//查询分页数据
func RetailsPageList(params *RetailsQueryParam) ([]*Retails, int64) {
	query := orm.NewOrm().QueryTable(RetailsTableName()).RelatedSel("Archives")
	data := make([]*Retails, 0)
	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	if params.ArcId > 0 {
		query = query.Filter("archives_id", params.ArcId)
	}
	if len(params.IsPayment) > 0 { //已支付
		sp := strings.Split(params.IsPayment, ",")
		query = query.Filter("IsPayment__in", sp)
	}

	if len(params.ArchivesName) > 0 {
		query = query.Filter("Archives__Realname", params.ArchivesName)
	}
	if len(params.ArchivesMobile) > 0 {
		query = query.Filter("Archives__Mobile", params.ArchivesMobile)
	}
	if len(params.Business) > 0 {
		query = query.Filter("business_name", params.Business)
	}

	if len(params.StartDate) > 0 {
		query = query.Filter("created_at__gte", utils.GetDateParse(params.StartDate))
	}
	if len(params.EndDate) > 0 {
		query = query.Filter("created_at__lte", utils.GetDateParse(params.EndDate)+86400)
	}

	if len(params.CreatedBy) > 0 {
		query = query.Filter("CreatedBy", params.CreatedBy)
	}
	if len(params.PickUpType) > 0 {
		query = query.Filter("pick_up_type", params.PickUpType)
	}
	if len(params.ManualNumber) > 0 {
		query = query.Filter("manual_number", params.ManualNumber)
	}

	query = query.Filter("department_id", params.Depid)

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total

}

func queryRetailsTimeSoltSeter(starttime, endtime int64, relatesel ...interface{}) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(RetailsTableName())
	if len(relatesel) > 0 {
		query = query.RelatedSel(relatesel...)
	} else {
		query = query.RelatedSel("Archives")
	}
	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("created_at__gte", starttime).And("created_at__lte", endtime))
	query = query.SetCond(cond)

	return query
}

//按时间段获取销售数据
func QueryRetailsTimeSoltSeter(curuser BackendUser, starttime, endtime int64, relatesel ...interface{}) []*Retails {

	data := make([]*Retails, 0)
	queryRetailsTimeSoltSeter(starttime, endtime, relatesel...).Filter("department_id", curuser.DepartmentId).Limit(-1).OrderBy("-id").All(&data)

	return data
}

//修改销售信息
func (a *Retails) RetailsEdit(fileds ...string) error {
	a.UpdatedAt = time.Now().Unix()
	a.UpdatedBy = CurLoginUserInfo.RealName

	if _, err := orm.NewOrm().Update(a, fileds...); err != nil {
		return err
	}

	return nil
}

//按时间段获取零售count
func QueryRetailsTimeSoltSeterCount(starttime, endtime int64) int64 {

	count, _ := queryRetailsTimeSoltSeter(starttime, endtime).Count()

	return count
}

//获取一个单据所有信息
func QueryRetailsDetails(id int64) (*Retails, error) {

	retail := new(Retails)
	retail.Id = id
	if err := orm.NewOrm().Read(retail); err != nil {
		return nil, err
	}
	//获取data数据
	retailData := make([]*RetailsData, 0)
	if _, err := orm.NewOrm().QueryTable(RetailsDataTableName()).RelatedSel("Products").Filter("retails_id", retail.Id).All(&retailData); err != nil {
		return nil, err
	}
	retail.RetailsData = retailData

	//获取档案数据
	archive := new(Archives)
	archive.Id = retail.Archives.Id
	if err := orm.NewOrm().Read(archive); err == nil {
		retail.Archives = archive
	}
	//获取验光数据
	if optometry, err := GetOptometryById(retail.Optometry.Id); err == nil {
		retail.Optometry = optometry
	}
	return retail, nil
}

func CreateRetailsDocumentNumber(c *BackendUser) string {
	var documentNumber string = ""
	stat := utils.GetDateParse(time.Now().Format("2006-01-02"))
	end := stat + 86400
	documentNumber = fmt.Sprintf("%s%06d", time.Now().Format("20060102150405"), QueryRetailsTimeSoltSeterCount(stat, end)+1)
	return documentNumber
}
